<?php

namespace App\Services\MakeCouponsUsePoints;

use App\Models\User;
use App\Models\Coupon;
use App\Models\Activity;
use App\Models\PointsProductRecord;
use App\Models\CouponRecord;
use App\Models\SeckillProduct;
use App\Models\ProductExpress;
use App\Models\ProductExtraExpress;
use Brick\Math\RoundingMode;
use App\Events\OrderCreatedEvent;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;

class MakeCouponsUseArivity
{
	protected ?User $user = null;


	public function __construct(
		User $user,
		$coupon_id = 0,
		$activity_id = 0
		)
	{
		$this->user = $user;
		$this->coupon_id = $coupon_id;
		$this->activity_id = $activity_id;
	}

	protected function create()
	{
		DB::transaction(function () {
			$activity = Activity::find($this->activity_id);
			$coupon = Coupon::find($this->coupon_id);

			if($coupon->is_date==1){
				$expiredAt =  $coupon->end_time;
			}else{

				$expiredAt =  date("Y-m-d",time())." ".$coupon->no_date_end_at;
			}
			


			if(strtotime($activity->acticity_ended_at) < time()){
				fail('该活动已结束！');
			}
			if(strtotime($expiredAt) < time()){
				fail('该优惠卷已不可使用！');
			}

			$coupon->decrement("total");
			$this->record = $this->user->couponRecords()->create(["activity_id"=>$this->activity_id,"coupon_id"=>$this->coupon_id,"expired_at"=>$expiredAt]);



		});

		return $this->record;
	}

	

	public function make()
	{
		return $this->create();
	}
}
